package package1;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 * TennisBros, minijuego de tenis temático
 *
 * @author Luis Angel Arranz Peinado
 */
public class JFrame extends javax.swing.JFrame implements Runnable {

    int xRaqueta = 200, yRaqueta = 285, wRaqueta = 80, hRaqueta = 20;
    int xSeta = 0, ySeta = -50, wSeta = 50, hSeta = 50;
    int xBrick = -90, yBrick = 70, wBrick = 50, hBrick = 50;
    int xMovSeta = 1, yMovSeta = 1, xMovBrick = 1, yMovBrick = 1;
    int xMouse, yMouse;
    int i, velocidad = 10, puntos = 0, record = 0;
    BufferStrategy buffer;
    Dimension dimensionJFrame;
    Image imgSeta, imgFondo, imgBrick, imgMario;
    Rectangle rectSeta, rectRaqueta, rectBrick;
    Thread hilo;

    /**
     * Constructor de JFrame
     */
    public JFrame() {
        initComponents();
        this.setSize(480, 330);
        dimensionJFrame = getSize();
        imgFondo = new ImageIcon("src/images/fondo.jpg").getImage();
        imgSeta = new ImageIcon("src/images/seta_green.png").getImage();
        imgBrick = new ImageIcon("src/images/brick.png").getImage();
        //imgMario = new ImageIcon("src/images/mario.png").getImage();
        rectSeta = new Rectangle(xSeta, ySeta, wSeta, hSeta);
        rectRaqueta = new Rectangle(xRaqueta, yRaqueta, wRaqueta, hRaqueta);
        rectBrick = new Rectangle(xBrick, yBrick, wBrick, hBrick);
        createBufferStrategy(2); // eliminar parpadeo
        buffer = this.getBufferStrategy();
        hilo = new Thread(this);
        hilo.start();
    }

    /**
     * Crea y convierte gráfico 2D
     */
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = null;
        try {
            g2 = (Graphics2D) buffer.getDrawGraphics();
            paint(g2);
        } finally {
            g2.dispose();
        }
        buffer.show();
    }

    /**
     * Realiza gráfico 2D
     */
    public void paint(Graphics2D g2) {
        super.paintComponents(g2);
        g2.drawImage(imgFondo, 0, 0, dimensionJFrame.width, dimensionJFrame.height, rootPane);
        g2.drawImage(imgSeta, xSeta, ySeta, wSeta, hSeta, rootPane);
        g2.drawImage(imgBrick, xBrick, yBrick, wBrick, hBrick, rootPane);
        //g2.drawImage(imgMario, xRaqueta, yRaqueta, 100, 100, rootPane);
        g2.setColor(Color.BLACK);
        g2.fillRect(xRaqueta, yRaqueta, wRaqueta, hRaqueta);
        g2.setFont(new Font("Arial", Font.PLAIN, 24));
        g2.drawString("Toques: " + puntos, jPanel1.getX() + 10, jPanel1.getY() + 53);
        g2.setFont(new Font("Arial", Font.PLAIN, 18));
        g2.drawString("Record: " + record, jPanel1.getWidth() - 100, jPanel1.getY() + 53);
    }

    /**
     * Realiza el movimiento
     */
    @Override
    public void run() {

        while (true) {

            rectSeta.setBounds(xSeta, ySeta, wSeta, hSeta);
            rectRaqueta.setBounds(xRaqueta, yRaqueta, wRaqueta, hRaqueta);
            rectBrick.setBounds(xBrick, yBrick, wBrick, hBrick);

            /*
             * MOVIMIENTOS DE LA SETA
             */

            // Limite izquierdo
            if (xSeta + xMovSeta < 0) {
                xMovSeta = 1;
            }

            // Limite derecho
            if (xSeta + xMovSeta > jPanel1.getWidth() - wSeta) {
                xMovSeta = - 1;
            }

            // Limite superior
            if (ySeta + yMovSeta < 0 + (hSeta / 2)) {
                yMovSeta = 1;
            }

            // Limite inferior
            if (ySeta + yMovSeta > jPanel1.getHeight() - (hSeta / 2)) {
                //ySpeed =- 1;
                int x = JOptionPane.showConfirmDialog(this, "Has obtenido " + puntos
                        + " puntos, ¿Quieres jugar de nuevo?", "Game Over", JOptionPane.OK_OPTION);
                if (x == JOptionPane.YES_OPTION) {
                    if (puntos > record) {
                        record = puntos;
                    }
                    puntos = 0;
                    velocidad = 10;
                    ySeta = 20;
                    xBrick = -90;
                } else if (x == JOptionPane.NO_OPTION) {
                    System.exit(0);
                }
            }

            /*
             * MOVIMIENTOS DEL LADRILLO (BRICK)
             */

            // Limite izquierdo
            if (xBrick < 10) {
                xMovBrick = 1;
            }

            // Limite derecho
            if (xBrick > jPanel1.getWidth() - wBrick) {
                xMovBrick = - 1;
            }

            /*
             * INTERSECCIONES O REBOTES
             */

            // Intersección superior con la Raqueta
            if (rectSeta.intersects(rectRaqueta) && yMovSeta == 1) {
                puntos++;
                yMovSeta = - 1; // movimiento de la pelota
                if (velocidad != 3) {
                    velocidad = velocidad - 1;
                }
            }

            // Intersección con el Brick
            if (rectSeta.intersects(rectBrick)) {
                //if (yMovSeta == -1) {
                    yMovSeta = 1;
                //}
                /*if (yMovSeta == 1) {
                    yMovSeta = -1;
                }
                if (xMovSeta == -1) {
                    xMovSeta = 1;
                }
                if (xMovSeta == 1) {
                    xMovSeta = -1;
                }*/
            }

            // Las siguientes lineas hace que se mueva
            xSeta = xSeta + xMovSeta;
            ySeta = ySeta + yMovSeta;
            if (puntos >= 5) {
                xBrick = xBrick + xMovBrick;
            }

            try {
                hilo.sleep(velocidad);
            } catch (InterruptedException e) {
            }

            repaint();

        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TennisBros");
        setResizable(false);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));

        jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                jPanel1MouseDragged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 394, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 314, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel1);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * EVENTOS DE TECLAS
     */
    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed

        switch (evt.getKeyCode()) {

            case KeyEvent.VK_LEFT:
                if (xRaqueta > 5) {
                    xRaqueta -= +30;
                }
                break;
            case KeyEvent.VK_RIGHT:
                if (xRaqueta < jPanel1.getWidth() - (wRaqueta + 3)) {
                    xRaqueta += 30;
                }
                break;
            case '-':
                velocidad += 5;
                break;
            case 'r':
                xSeta = 150;
                ySeta = 60;
                break;
        }

        repaint();

    }//GEN-LAST:event_formKeyPressed

    private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseDragged
        // Se establecen las coodernadas de para la posicion del mouse

        xMouse = evt.getX();
        yMouse = evt.getY();

        //if (xMouse > xRaqueta && xMouse < xRaqueta + wRaqueta) {
        if (xMouse > (jPanel1.getX() + 40) && xMouse < jPanel1.getWidth() - 45) {
            xRaqueta = evt.getX() - 35;
        }
        //}

    }//GEN-LAST:event_jPanel1MouseDragged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
}